﻿using System;
using System.Globalization;
using AudioComponent;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
using Services;
using WAG.Menu;
using WAG.Resources;

namespace WAG
{
  /// <summary>
  /// In questo game va integrato un menú che si occupa di avviare i livelli.
  /// il menú funziona cosí: quando un livello va lanciato, invoca la Dispose
  /// su tutti i Components e li toglie dalla lista dei Components; svuota
  /// anche i Services e poi ricrea i components desiderati per il livello
  /// selezionato. In questo modo facciamo ogni volta piazza pulita.
  /// </summary>
  public class SpaceBattleGame : Microsoft.Xna.Framework.Game
  {
    public static int DEFAULT_SCR_WIDTH = 800;
    public static int DEFAULT_SCR_HEIGHT = 480;

    GraphicsDeviceManager graphics;
    SpriteBatch sprite_batch;

    public SpaceBattleGame()
    {
      graphics = new GraphicsDeviceManager(this);
      Content.RootDirectory = "Content";

      Strings.Culture = CultureInfo.CurrentCulture;

      /// Il primo passo consiste nel crearsi un servizio di configurazione riferito
      /// ai modelli principali: nave del giocatore, del nemico, proiettile semplice
      /// e missile.
      this.Services.AddService(typeof(ConfigurationService), ConfigurationService.GetDefaulConfiguration());
      this.Services.AddService(typeof(GraphicsDeviceManager), graphics);

      graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
      graphics.PreferredBackBufferWidth = 800;
      graphics.PreferredBackBufferHeight = 480;

      graphics.ApplyChanges();

#if WINDOWS || XBOX
            //graphics.PreferredBackBufferWidth = 480;
            //graphics.PreferredBackBufferHeight = 800;
            graphics.IsFullScreen = false;
#else
      //graphics.PreferredBackBufferWidth = 480;
      //graphics.PreferredBackBufferHeight = 800;
      graphics.IsFullScreen = true;
#endif
      AudioManager.Volume = MediaPlayer.Volume;
      SoundTrackManager.Volume = 1.0f;
      StateManager.SelectIntroScreen(this);
      //StateManager.SelectLanguagesScreen(this);
      //StateManager.SelectMenu(this);

      IsMouseVisible = true;
      IsFixedTimeStep = true;
      TargetElapsedTime = TimeSpan.FromSeconds(1.0 / 30.0);

      graphics.SynchronizeWithVerticalRetrace = true;
      //facciamo partire la colonna sonora
      //st_manager = new SoundTrackManager(this);
      //this.Components.Add(st_manager);
      //st_manager.Play();



    }

    protected override void Initialize()
    {
      sprite_batch = new SpriteBatch(GraphicsDevice);
      Services.AddService(typeof(SpriteBatch), sprite_batch);
      MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
      base.Initialize();
    }

    WakaGarbageModeEntry wakastats;

    void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
    {
      var audio_service = this.Services.GetService(typeof(IAudioManager)) as AudioManager;



      switch (MediaPlayer.State)
      {
        case MediaState.Playing:

          //orribile!! da ottimizare in futuro
          if (audio_service != null)
            audio_service.OnaudioOff();
          else
            AudioManager.Volume = 0;

          wakastats = Leaderboard.GetWakaModeStats();
          Leaderboard.SaveWakaModeStats(new WakaGarbageModeEntry(
                                              wakastats.ShowAlwaysTutorial,
                                              wakastats.GarbageDestroyed,
                                              wakastats.LevelScore,
                                              wakastats.Level,
                                              wakastats.GreenTrashBinState,
                                              wakastats.YellowTrashBinState,
                                              wakastats.BlueTrashBinState,
                                              wakastats.ManHoleState,
                                              wakastats.EarthLife,
                                              wakastats.TotalGameTime,
                                              wakastats.TimeToNextLevel,
                                              false
                                              ));
          break;
          /*
        case MediaState.Paused:
          if (audio_service != null)
            audio_service.OnaudioOn();
          else
           AudioManager.Volume = 1;

          wakastats = Leaderboard.GetWakaModeStats();
          Leaderboard.SaveWakaModeStats(new WakaShipModeEntry(
                                              wakastats.showAlwaysTutorial,
                                              true,
                                              wakastats.AsteroidHits,
                                              wakastats.TimeToAddOrRemove,
                                              wakastats.TimeToEndGame,
                                              wakastats.ShipsDestroyed,
                                              wakastats.BossDestroyed,
                                              wakastats.LevelScore,
                                              wakastats.Level,
                                              wakastats.TotalGameTime
                                              ));
          break;
           */
        default:
          break;
      }
    }


    protected override void LoadContent()
    {
      GraphicsDevice.Clear(Color.Black);

      base.LoadContent();

      //var t = new Thread(AsynchDataLoader);
      //t.Start();
    }

    protected override void Dispose(bool disposing)
    {
      this.Services.RemoveService(typeof(SpriteBatch));
      this.Services.RemoveService(typeof(ConfigurationService));
      base.Dispose(disposing);
    }

    internal void Draw()
    {
      this.Draw(new GameTime(TimeSpan.Zero, TimeSpan.Zero));
    }

    private void AsynchDataLoader()
    {
      //// Main Menù
      //Content.Load<Texture2D>("Menu/bg");
      //Content.Load<Texture2D>("Menu/box_top");
      //Content.Load<Texture2D>("Menu/box_mid");
      //Content.Load<Texture2D>("Menu/box_btm");
      //Content.Load<Texture2D>("Menu/g_title");
      //Content.Load<SpriteFont>("Fonts/OCRAExtended30");
      //Content.Load<SpriteFont>("Fonts/OCRAExtended16");

      //// Ship Selection
      //Content.Load<Texture2D>("Menu/title_bg");
      //Content.Load<Texture2D>("Menu/stat_bg");
      //Content.Load<Texture2D>("Menu/confirm_box");
      //Content.Load<Texture2D>("Menu/buy_box");
      //Content.Load<Texture2D>("Menu/arrow_ss");
      //Content.Load<SpriteFont>("Fonts/OCRAExtended32");
      //Content.Load<SpriteFont>("Fonts/OCRAExtended18");
      //Content.Load<SpriteFont>("Fonts/Orator14");
      //Content.Load<SpriteFont>("Fonts/VerySmall");
      //Content.Load<Texture2D>("UI/WhitePixel");
      //Content.Load<SoundEffect>("Audio/error");

      // Various Model
      var c = ConfigurationService.GetDefaulConfiguration();

      //for (int i = 0; i < c.Ships.Count; i++)
      //    Content.Load<Model>(c.Ships[i].ModelPath);

      Content.Load<Model>("Planets/sphere");

      //var cube_faces = new[]{
      //    "PositiveX",
      //    "NegativeX",
      //    "PositiveY",
      //    "NegativeY",
      //    "PositiveZ",
      //    "NegativeZ"
      //  };

      //var bg_path = new[] {
      //    "Backgrounds/atlantis/",
      //    "Backgrounds/hope_and_glory/",
      //    "Backgrounds/yellow_ship/",
      //    "Backgrounds/" };

      //for (int i = 0; i < bg_path.Length; i++)
      //    for (int j = 0; j < cube_faces.Length; j++)
      //        Content.Load<Texture2D>(bg_path[i] + cube_faces[j]);

      Content.Load<Model>(c.AsteroidModel);
      Content.Load<Model>(c.LaserModel);
      Content.Load<Model>(c.NukeModel);
      Content.Load<Model>(c.SwarmModel);

      // Vittoria e sconfitta
      Content.Load<Texture2D>("LevelFinished/bg");
      Content.Load<Texture2D>("LevelFinished/defeat_bg");
      Content.Load<Texture2D>("LevelFinished/hor_left");
      Content.Load<Texture2D>("LevelFinished/hor_right");
      Content.Load<Texture2D>("LevelFinished/ver_left");
      Content.Load<Texture2D>("LevelFinished/ver_right");

      Content.Load<Texture2D>("UI/upper_dock");
    }
  }
}
